<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + '黑白名单'"
    width="500px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>
<script>
import {
  addWhiteBlack,
  detailWhiteBlack,
  editWhiteBlack,
} from "@/api/sub/portrayal";
import { replaceDigit } from "@/utils/index";
import { typeAndLabelLv2Code } from "@/api/system/dict/data";
import FormButton from "@/components/FormButton";
export default {
  dicts: [
    "energy_subarea_type", // 分区类别
    "energy_subarea_child_type", // 分区子类
  ],
  components: {
    FormButton,
  },
  props: {
    id: { type: [Number, String], default: "" },
    visible: { type: Boolean, default: false },
  },
  data() {
    return {
      live2Codes: [],
      loading: false,
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              subareaType: [
                {
                  required: true,
                  message: "请选择分区类别",
                  trigger: "change",
                },
              ],
              subareaChildType: [
                {
                  required: true,
                  message: "请选择分区子类",
                  trigger: "change",
                },
              ],
              deviceName: [
                { required: true, message: "请填写用电设备", trigger: "blur" },
              ],
              amplitudeModulationPercent: [
                { required: true, message: "调幅比例不能为空" },
                { type: "number", message: "调幅比例必须为数字值" },
              ],
              kwh: [
                { required: true, message: "请填写常规能耗", trigger: "blur" },
              ],
              dayOfUseTime: [
                {
                  required: true,
                  message: "请填写常规日时长",
                  trigger: "blur",
                },
              ],

              suggestChangeTime: [
                {
                  required: true,
                  message: "请选择建议更换日期",
                  trigger: "change",
                },
              ],
              whiteBlackFlag: [
                {
                  required: true,
                  message: "请选择黑白名单标志",
                  trigger: "change",
                },
              ],
            },
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            subareaType: {
              typeName: "el-select",
              label: "分区类别:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_subarea_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().subareaType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("subareaType", value);
                          that.$refs?.form?.setFieldValue(
                            "subareaChildType",
                            ""
                          );
                          that.getTypeAndLabelLv2Code(value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            subareaChildType: {
              typeName: "el-select",
              label: "分区子类:",
              clearable: true,
              render: (h) => {
                let that = this;
                let arr = that.live2Codes;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().subareaChildType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "subareaChildType",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { dictLabel, dictValue } = item;
                        return h("el-option", {
                          props: {
                            label: dictLabel,
                            value: Number(dictValue),
                            key: dictValue,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            deviceName: {
              typeName: "el-input",
              label: "用电设备",
            },
            amplitudeModulationPercent: {
              typeName: "el-input-number",
              label: "调幅比例(%)",
              precision: 2,
            },
            kwh: {
              typeName: "el-input",
              label: "常规能耗",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入常规能耗"
                      value={this.$refs?.form?.getFieldsValue().kwh}
                      clearable
                      onInput={(value) => this.keyFixAmount(value, "kwh")}
                    >
                      <template slot="append">kwh</template>
                    </el-input>
                  </div>
                );
              },
            },
            dayOfUseTime: {
              typeName: "el-input",
              label: "常规日时长",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入常规日时长"
                      value={this.$refs?.form?.getFieldsValue().dayOfUseTime}
                      clearable
                      onInput={(value) =>
                        this.keyFixAmount(value, "dayOfUseTime")
                      }
                    >
                      <template slot="append">h/d</template>
                    </el-input>
                  </div>
                );
              },
            },
            whiteBlackFlag: {
              label: "黑白名单标志",
              typeName: "el-select",
              clearable: true,
              render: (h) => {
                let that = this;
                let arr = [
                  {
                    label: "白名单",
                    value: 1,
                  },
                  {
                    label: "黑名单",
                    value: 2,
                  },
                ];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().whiteBlackFlag;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "whiteBlackFlag",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },

  methods: {
    getTypeAndLabelLv2Code(val) {
      let data = this.dict.type.energy_subarea_type.find(
        (item) => item.value == val
      );
      if (Object.keys(data).length > 0) {
        typeAndLabelLv2Code(
          "energy_subarea_child_type",
          data.raw.dictCode
        ).then((response) => {
          this.live2Codes = response.data;
        });
      }
    },
    getInfo() {
      detailWhiteBlack(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          this.$refs?.form?.setFieldsValue(newData);
          this.getTypeAndLabelLv2Code(newData.subareaType);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!3001007");
        });
    },
    keyFixAmount(value, key) {
      if (key == "dayOfUseTime") {
        if (Number(value) > 24) {
          this.$message.warning("不能大于24小时");
          this.$refs?.form?.setFieldValue(key, "");
          return false;
        }
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 1));
      } else {
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 2));
      }
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            ...this.$refs.form.getFieldsValue(),
          };
          this.loading = true;
          if (this.id) {
            editWhiteBlack(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!301006");
              });
          } else {
            addWhiteBlack(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!301005");
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
}
</style>
